package cn.t.keycloak.demo.mfa.sms.rest;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import cn.t.keycloak.demo.mfa.sms.spi.ISmsSenderProvider;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import lombok.extern.slf4j.Slf4j;
import org.keycloak.connections.jpa.JpaConnectionProvider;
import org.keycloak.models.KeycloakSession;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 陶敏麒
 * @date 2023/11/20 15:19
 */
@Slf4j
public class SmsResource {

    private final KeycloakSession session;

    public SmsResource(KeycloakSession session) {
        this.session = session;
    }

    @Path("/sendLoginSmsCode")
    @Produces(MediaType.APPLICATION_JSON)
    @GET
    public Map<String, Object> sendLoginSmsCode(@QueryParam("phoneNumber") String phoneNumber) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 1);
        if (!Validator.isMobile(phoneNumber)) {
            // 直接抛异常会返回html响应
            // throw new BadRequestException("手机号不合法");
            resultMap.put("msg", "手机号码不合法");
            return resultMap;
        }
        // 生成验证码
        String randomNumbers = RandomUtil.randomNumbers(6);
        log.info(">>>>向手机[{}]发送登录验证码[{}]", phoneNumber, randomNumbers);
        int expires = this.session.getProvider(ISmsSenderProvider.class).sendVerificationCode(phoneNumber, randomNumbers);
        resultMap.put("code", 0);
        resultMap.put("data", expires);
        return resultMap;
    }

    @Path("/sendMfaSmsCode")
    @Produces(MediaType.APPLICATION_JSON)
    @GET
    public Map<String, Object> sendSmsCode(@QueryParam("phoneNumber") String phoneNumber) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 1);
        if (!Validator.isMobile(phoneNumber)) {
            // 直接抛异常会返回html响应
            // throw new BadRequestException("手机号不合法");
            resultMap.put("msg", "手机号码不合法");
            return resultMap;
        }

        var em = this.session.getProvider(JpaConnectionProvider.class).getEntityManager();
        // 先查询是否存在
        var duplicate = em.createNativeQuery("SELECT 1 FROM VERIFY_PHONE_LOG WHERE REALM_ID = ?1 AND PHONE_NUMBER = ?2");
        duplicate.setParameter(1, this.session.getContext().getRealm().getId());
        duplicate.setParameter(2, phoneNumber);
        if (duplicate.getResultList() != null && !duplicate.getResultList().isEmpty()) {
            log.warn("手机[{}]已经被认证了", phoneNumber);
            resultMap.put("msg", "手机号码已经被他人绑定了");
            return resultMap;
        }

        // 生成验证码
        String randomNumbers = RandomUtil.randomNumbers(6);
        log.info(">>>>开始向手机[{}]发送验证码[{}]", phoneNumber, randomNumbers);
        int expires = this.session.getProvider(ISmsSenderProvider.class).sendVerificationCode(phoneNumber, randomNumbers);
        resultMap.put("code", 0);
        resultMap.put("data", expires);
        return resultMap;
    }
}
